//
//  ScanViewController.m
//  YYQRScaning
//
//  Created by 蓓蕾 on 2021/8/12.
//  Copyright © 2021 Yang. All rights reserved.
//

#import "ScanViewController.h"
#import <AVFoundation/AVFoundation.h>

/** 扫描框的宽度与高度 */
static const NSInteger staticHeight = 250;
/** 扫描框距离顶部的距离，设置为0 是，扫描框居中 */
static const NSInteger staticTopMargin = 140;

//颜色(默认支付宝蓝)
#define STYLECOLOR [UIColor colorWithRed:57/255.f green:187/255.f blue:255/255.f alpha:1.0]

@interface ScanViewController ()<AVCaptureMetadataOutputObjectsDelegate>

@property (nonatomic , strong ) AVCaptureDevice         *   device;
@property (nonatomic , strong ) AVCaptureDeviceInput    *   input;
@property (nonatomic , strong ) AVCaptureMetadataOutput *   output;
@property (nonatomic , strong ) AVCaptureSession        *   session;
@property (nonatomic , strong ) AVCaptureVideoPreviewLayer *previewlayer;
@property (nonatomic , strong ) UIView                  *   hudView;

@end

@implementation ScanViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [self initScanConfig];
}

-(void)initScanConfig
{
    //扫描范围限制
    CGRect outPutRect = [self rectOfInterestByScanViewRect:CGRectMake(CGRectGetWidth(self.view.bounds) / 2 - staticHeight / 2,staticTopMargin,staticHeight,staticHeight)];
    if (staticTopMargin == 0) {
        outPutRect = CGRectMake(CGRectGetWidth(self.view.bounds) / 2 - staticHeight / 2, CGRectGetHeight(self.view.bounds) / 2 - staticHeight / 2, staticHeight, staticHeight);
        
        outPutRect = [self rectOfInterestByScanViewRect:outPutRect];
    }
    self.view.backgroundColor = UIColor.grayColor;
    AVAuthorizationStatus authorizationStatus = [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeVideo];
    BOOL isAvailableA = authorizationStatus == AVAuthorizationStatusRestricted || authorizationStatus == AVAuthorizationStatusDenied;
    if([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera] && isAvailableA == NO){//判断相机
        _device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
        _input = [AVCaptureDeviceInput deviceInputWithDevice:_device error:nil];
        _output = [[AVCaptureMetadataOutput alloc] init];
        [_output setMetadataObjectsDelegate:self queue:dispatch_get_main_queue()];
        [_output setRectOfInterest:outPutRect];//扫描范围限制
        _session = [[AVCaptureSession alloc] init];
        [_session setSessionPreset:AVCaptureSessionPresetHigh];
        if ([_session canAddInput:_input]) {
            [_session addInput:_input];
        }
        if ([_session canAddOutput:_output]) {
            [_session addOutput:_output];
        }
        _output.metadataObjectTypes = @[AVMetadataObjectTypeQRCode];
        _previewlayer = [AVCaptureVideoPreviewLayer layerWithSession:_session];
        _previewlayer.videoGravity = AVLayerVideoGravityResizeAspectFill;
        _previewlayer.frame = self.view.layer.bounds;
        [self.view.layer insertSublayer:_previewlayer atIndex:0];
        [_session startRunning];

    }else{//相机不可用
        if (![UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
            NSLog(@"相机不可用");
            UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"温馨提示" message:@"您的相机处于不可使用状态，请确认您的相机是否已损坏" preferredStyle:UIAlertControllerStyleAlert];
            UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
                
            }];
            [alertController addAction:cancelAction];
            [self presentViewController:alertController animated:YES completion:nil];
        }
        else if (!isAvailableA)
        {
            NSLog(@"相机权限受限");
            UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"温馨提示" message:@"请您设置允许扫描器访问您的相机\n设置>隐私>相机>扫描器" preferredStyle:UIAlertControllerStyleAlert];
            UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
                
            }];
            UIAlertAction *confirmAction = [UIAlertAction actionWithTitle:@"设置" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                NSURL *url = [NSURL URLWithString:UIApplicationOpenSettingsURLString];
                if ([[UIApplication sharedApplication] canOpenURL:url]) {
                    [[UIApplication sharedApplication] openURL:url options:@{} completionHandler:nil];
                }
            }];
            [alertController addAction:cancelAction];
            [alertController addAction:confirmAction];
            [self presentViewController:alertController animated:YES completion:nil];
        }
        
    }
    [self.view addSubview:self.hudView];
    
    
    
    UIButton *lightAction = [UIButton buttonWithType:UIButtonTypeCustom];
    [self.view addSubview:lightAction];
    lightAction.frame = CGRectMake(kScreenWidth / 2 - 60 / 2, kScreenHeight - 80 - 30 - NAV_HEIGHT, 80, 80);
    [lightAction setImage:[UIImage imageNamed:@"light_off"] forState:UIControlStateNormal];
    [lightAction setImage:[UIImage imageNamed:@"light_on"] forState:UIControlStateSelected];
    [lightAction addTarget:self action:@selector(lightMethod:) forControlEvents:UIControlEventTouchUpInside];
}

-(void)lightMethod:(UIButton *)sender
{
    if ([self.input.device hasTorch]) {
        AVCaptureTorchMode torch = self.input.device.torchMode;
        
        switch (_input.device.torchMode) {
            case AVCaptureTorchModeAuto:
                break;
            case AVCaptureTorchModeOff:
                torch = AVCaptureTorchModeOn;
                sender.selected = YES;
                break;
            case AVCaptureTorchModeOn:
                torch = AVCaptureTorchModeOff;
                sender.selected = NO;
                break;
            default:
                break;
        }
        
        [_input.device lockForConfiguration:nil];
        _input.device.torchMode = torch;
        [_input.device unlockForConfiguration];
    }
}

-(void)showAlertWithTitle:(NSString *)title withInfo:(nullable NSString *)info withCancelTitle:(nullable NSString *)cancelString withConfirmTitle:(NSString *)confirmString withResultBlock:(void(^)(void))result
{
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:title message:info preferredStyle:UIAlertControllerStyleAlert];
    
    if (cancelString.length > 0) {
        UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:cancelString style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
            
        }];
        [alertController addAction:cancelAction];
    }
    
    UIAlertAction *confirmAction = [UIAlertAction actionWithTitle:confirmString style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        if (result) {
            result();
        }
    }];
    [alertController addAction:confirmAction];
    [self presentViewController:alertController animated:YES completion:nil];
}

- (CGRect)rectOfInterestByScanViewRect:(CGRect)rect {
    
    CGFloat width = CGRectGetWidth(self.view.frame);
    CGFloat height = CGRectGetHeight(self.view.frame);
    
    CGFloat x = rect.origin.y/ height;
    CGFloat y = rect.origin.x/ width;
    
    CGFloat w = CGRectGetHeight(rect) / height;
    CGFloat h = CGRectGetWidth(rect) / width;
    
    return CGRectMake(x, y, w, h);
}


#pragma mark - AVCaptureMetadataOutputObjectsDelegate
- (void)captureOutput:(AVCaptureOutput *)output didOutputMetadataObjects:(NSArray<__kindof AVMetadataObject *> *)metadataObjects fromConnection:(AVCaptureConnection *)connection
{
    if (metadataObjects.count > 0) {
        [_session stopRunning];
        AVMetadataMachineReadableCodeObject *metadataObject = metadataObjects.firstObject;
        NSString *resultString = metadataObject.stringValue;
        NSLog(@"扫描结果：%@",resultString);
        __weak typeof(self) weakSelf = self;
        [self showAlertWithTitle:@"扫描结果" withInfo:resultString withCancelTitle:nil withConfirmTitle:@"确定" withResultBlock:^{
            [weakSelf starScaning];
        }];
//        !self.backQRCodeURL ? : self.backQRCodeURL(metadataObject.stringValue);
    }
}

-(void)starScaning
{
    if (!_session.isRunning) {
//        NSLog(@"未处于扫描状态，开始扫描");
        [_session startRunning];
    }
//    else
//    {
//        NSLog(@"已处于扫描状态，无需操作");
//    }
}

#pragma mark - lazy
//懵层
- (UIView *)hudView
{
    if (!_hudView) {
        _hudView = [[UIView alloc] initWithFrame:self.view.bounds];
        CGFloat x = (self.view.frame.size.width - staticHeight)*0.5;
        CGFloat y = staticTopMargin > 0 ? staticTopMargin : (self.view.frame.size.height - staticHeight)*0.5;
        CGFloat height = staticHeight;
        //镂空
        CGRect qrRect = CGRectMake(x,y,height, height);
        UIBezierPath *path = [UIBezierPath bezierPathWithRoundedRect:self.view.frame cornerRadius:0];
        UIBezierPath *circlePath = [UIBezierPath bezierPathWithRect:qrRect];
        [path appendPath:circlePath];
        [path setUsesEvenOddFillRule:YES];
        CAShapeLayer *fillLayer = [CAShapeLayer layer];
        fillLayer.path = path.CGPath;
        fillLayer.fillRule = kCAFillRuleEvenOdd;
        fillLayer.fillColor = [UIColor colorWithRed:0/255.0 green:0/255.0 blue:0/255.0 alpha:0.4].CGColor;
        fillLayer.opacity = 0.5;
        [_hudView.layer addSublayer:fillLayer];

        //白色矩形
        UIBezierPath *bezierPath = [UIBezierPath bezierPathWithRect:CGRectMake(x, y, height, height)];
        CAShapeLayer *shapLayer = [CAShapeLayer layer];
        shapLayer.backgroundColor = UIColor.clearColor.CGColor;
        shapLayer.path = bezierPath.CGPath;
        shapLayer.lineWidth = 0.5;
        shapLayer.strokeColor = UIColor.whiteColor.CGColor;
        shapLayer.fillColor = UIColor.clearColor.CGColor;
        [_hudView.layer addSublayer:shapLayer];

        //绿色四个角落
        UIBezierPath *cornerBezierPath = [UIBezierPath bezierPath];

        [cornerBezierPath moveToPoint:CGPointMake(x, y+30)];//左上角
        [cornerBezierPath addLineToPoint:CGPointMake(x, y)];
        [cornerBezierPath addLineToPoint:CGPointMake(x+30, y)];

        [cornerBezierPath moveToPoint:CGPointMake(x+height-30, y)];//右上角
        [cornerBezierPath addLineToPoint:CGPointMake(x+height, y)];
        [cornerBezierPath addLineToPoint:CGPointMake(x+height, y+30)];

        [cornerBezierPath moveToPoint:CGPointMake(x+height, y+height-30)];//左上角
        [cornerBezierPath addLineToPoint:CGPointMake(x+height, y+height)];
        [cornerBezierPath addLineToPoint:CGPointMake(x+height-30, y+height)];

        [cornerBezierPath moveToPoint:CGPointMake(x+30, y+height)];//左上角
        [cornerBezierPath addLineToPoint:CGPointMake(x, y+height)];
        [cornerBezierPath addLineToPoint:CGPointMake(x, y+height-30)];

        CAShapeLayer *cornerShapLayer = [CAShapeLayer layer];
        cornerShapLayer.backgroundColor = UIColor.clearColor.CGColor;
        cornerShapLayer.path = cornerBezierPath.CGPath;
        cornerShapLayer.lineWidth = 3.0;
        cornerShapLayer.strokeColor = STYLECOLOR.CGColor;
        cornerShapLayer.fillColor = UIColor.clearColor.CGColor;
        [_hudView.layer addSublayer:cornerShapLayer];

        //光标
        CAGradientLayer *gradientLayer = [CAGradientLayer layer];
        gradientLayer.frame = CGRectMake(x+3, y+3, height-6, 1.5);
        gradientLayer.colors = [self colorWithBasicColor:STYLECOLOR];
        gradientLayer.startPoint = CGPointMake(0, 0.5);
        gradientLayer.endPoint = CGPointMake(1.0, 0.5);
        [gradientLayer addAnimation:[self positionBasicAnimate] forKey:nil];
        [_hudView.layer addSublayer:gradientLayer];
    }
    return _hudView;
}
//动画
- (CABasicAnimation *)positionBasicAnimate
{
    CGFloat x = (self.view.frame.size.width - staticHeight)*0.5;
    CGFloat y = staticTopMargin > 0 ? staticTopMargin : (self.view.frame.size.height - staticHeight)*0.5;
    CGFloat height = staticHeight;
    CABasicAnimation *animate = [CABasicAnimation animationWithKeyPath:@"position"];
    animate.removedOnCompletion = NO;
    animate.duration = 2.0;
    animate.fillMode = kCAFillModeRemoved;
    animate.repeatCount = HUGE_VAL;
    animate.fromValue = [NSValue valueWithCGPoint:CGPointMake(x+height*0.5, y+3)];
    animate.toValue = [NSValue valueWithCGPoint:CGPointMake(x+height*0.5, y+height-3)];
    animate.autoreverses = YES;
    return animate;
}

- (NSArray<UIColor *> *)colorWithBasicColor:(UIColor *)basicCoclor
{
    CGFloat R, G, B, amplitude;
    amplitude = 90/255.0;
    NSInteger numComponents = CGColorGetNumberOfComponents(basicCoclor.CGColor);
    NSArray *colors;
    if (numComponents == 4)
    {
        const CGFloat *components = CGColorGetComponents(basicCoclor.CGColor);
        R = components[0];
        G = components[1];
        B = components[2];
        colors = @[(id)[UIColor colorWithWhite:0.667 alpha:0.2].CGColor,
                   (id)basicCoclor.CGColor,
                   (id)[UIColor colorWithRed:R+amplitude > 1.0 ? 1.0:R+amplitude
                                        green:G+amplitude > 1.0 ? 1.0:G+amplitude
                                        blue:B+amplitude > 1.0 ? 1.0:B+amplitude alpha:1.0].CGColor,
                   (id)[UIColor colorWithRed:R+amplitude > 1.0 ? 1.0:R+amplitude*2
                                        green:G+amplitude > 1.0 ? 1.0:G+amplitude*2
                                        blue:B+amplitude > 1.0 ? 1.0:B+amplitude*2 alpha:1.0].CGColor,
                   (id)[UIColor colorWithRed:R+amplitude > 1.0 ? 1.0:R+amplitude
                                        green:G+amplitude > 1.0 ? 1.0:G+amplitude
                                        blue:B+amplitude > 1.0 ? 1.0:B+amplitude alpha:1.0].CGColor,
                   (id)basicCoclor.CGColor,
                   (id)[UIColor colorWithWhite:0.667 alpha:0.2].CGColor,];
    }else{
        colors = @[(id)basicCoclor.CGColor,
                   (id)basicCoclor.CGColor,];
    }
    return colors;
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
